<template>
  <van-address-list
    v-model="chosenAddress"
    :list="addressList"
    default-tag-text="默认"
    :add-button-text="
      route.query.isCart === '1' || route.query.goodsId
        ? '生成订单'
        : '新增地址'
    "
    @add="onAdd"
    @edit="onEdit"
  />
</template>

<script setup>
import { getAddressList } from "@/api/address";
import { onMounted, ref } from "@vue/runtime-core";
import { useRoute, useRouter } from "vue-router";

let route = useRoute();
let router = useRouter();
let addressList = ref([]);
let chosenAddress = ref(null);

onMounted(async () => {
  let arr = (await getAddressList({ limit: 100, page: 1 })).data.list || [];
  addressList.value = arr.map((item) => {
    return {
      id: item.id,
      name: item.name,
      tel: item.phone,
      address: item.province + item.city + item.town + item.detail,
      isDefault: item.is_default === 1,
    };
  });
  // 默认地址
  let defaultAddress = addressList.value.find(
    (item) => item.isDefault === true
  );
  // 默认选中
  chosenAddress.value = defaultAddress.id;
});

let onAdd = () => {
  // 判断是新增地址还是生产订单
  if (route.query.isCart) {
    // 购物车购买
    router.push(
      `/create-order?chosenGoods=${route.query.chosenGoods}&addressId=${chosenAddress.value}`
    );
  } else if(route.query.goodsId) {
    // 商品详情直接购买
    router.push(
      `/create-order?goodsId=${route.query.goodsId}&addressId=${chosenAddress.value}`
    );
  }else{
    router.push("/edit-address");
  }
};

let onEdit = (item) => {
  router.push(`/edit-address?id=${item.id}`);
};
</script>
